package com.sy.common.controller;

import com.sy.common.bean.ResultBean;
import com.sy.common.exception.ValidateException;
import com.sy.common.utils.ResultStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseController {
    protected ResultBean success(String msg) {
        return handler(ResultStatus.SUCCESS, msg, null);
    }

    protected ResultBean success(String msg, Object data) {
        return handler(ResultStatus.SUCCESS, msg, data);
    }

    protected ResultBean fail(String msg) {
        return handler(ResultStatus.FAIL, msg, null);
    }

    protected ResultBean fail(String msg, Object data) {
        return handler(ResultStatus.FAIL, msg, data);
    }

    /**
     * 后端校验
     * @param result
     */
    protected void validate(BindingResult result){
        List<FieldError> list = result.getFieldErrors();
        if (null!=list&&list.size()>0){
            Map error = new HashMap(); //存储作物字段
            list.forEach(o->{error.put(o.getField(),o.getDefaultMessage());});
            throw new ValidateException(error);
        }
    }
    ResultBean handler(ResultStatus status, String msg, Object data) {
        return new ResultBean<>(status.getCode(), msg, data);
    }
}
